package com.woniuxy.gateway.filter;

import cn.hutool.json.JSONUtil;
import com.woniuxy.gateway.common.GateWayResultCode;
import com.woniuxy.gateway.config.AuthConfig;
import com.woniuxy.security.util.JwtUtil;
import com.woniuxy.security.util.RsaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private AuthConfig authConfig;

    private AntPathMatcher pathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String uri = request.getURI().getPath();
        System.out.println(uri);
        boolean flag = false;
        for(String path : authConfig.getSecurityUrl()){
            if(pathMatcher.match(path,uri)){
                flag  = true;
                break;
            }
        }
        if(flag){
            String token = request.getHeaders().getFirst(authConfig.getHeader());
            if(StringUtils.isEmpty(token)){
                authError(response, GateWayResultCode.VALIDATE_FALL.getCode() ,GateWayResultCode.VALIDATE_FALL.getMessage());
            }
            token = token.replace(authConfig.getTokenStartWith()+" ","");
            //验证token
            try {
                Map claims = JwtUtil.parseToken(token, RsaUtil.getPublicKey(authConfig.getPubPath()));
                Long id = ((Integer) claims.get("id")).longValue();
                String username = (String) claims.get("username");
                String name =(String) claims.get("name");
                request = request.mutate().headers(h->{
                    h.add("memberId",id.toString());
                    h.add("username",username);
                    h.add("name",name);
                }).build();

                exchange = exchange.mutate().request(request).build();
            } catch (Exception e) {
                e.printStackTrace();
                authError(response,GateWayResultCode.TOKEN_FAIL.getCode(),GateWayResultCode.TOKEN_FAIL.getMessage());
            }
        }

        return chain.filter(exchange);
    }

    private Mono<Void> authError(ServerHttpResponse response, int code, String message) {
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        Map res = new HashMap<>();
        res.put("code",code);
        res.put("message",message);
        DataBuffer dataBuffer = response.bufferFactory().wrap(JSONUtil.toJsonStr(res).getBytes());
        return response.writeWith(Flux.just(dataBuffer));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
